package com.haitaoit.chengquan.base;

import android.Manifest;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Window;
import android.widget.ImageView;

import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.business.data.BaseHttp;
import com.haitaoit.chengquan.business.http.bean.ParamObj;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/5.
 */

public abstract class QBaseActivity extends AppCompatActivity {
    private   ProcessDialog       mProcessDialog;
    protected Handler             handler;
    private   ProgressDialog      mDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        //        setWindowStatusBarColor(getResources().getColor(R.color.black));
        setContentView(getContentView());
        //        initAppMsgBroad();
        initHandler();
        initView();
        initEvent();
        initData();
        initPerMission();
    }

    public abstract int getContentView();

    public abstract void initView();

    public abstract void initData();

    public abstract void initEvent();

    protected abstract void updateUI(Message msg);


    protected void initHandler() {

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case BaseHttp.START:
                        showProgressDialog();
                        break;

                    case BaseHttp.TOKEN_INVALID:
                        closeProgressDialog();
                        onTokenInvalid();
                        break;

                    case BaseHttp.FAILURE:
                        failureOperation(msg.obj);
                        closeProgressDialog();
                        break;
                    case BaseHttp.END:
                        closeProgressDialog();
                        break;
                    case BaseHttp.CHILD_INFO_INVLID:

                        closeProgressDialog();
                        updateUI(msg);
                        //                        editChildInfo();
                        break;
                    default:
                        updateUI(msg);
                        break;
                }
            }
        };
    }

    public void onTokenInvalid() {
        tokenInvalid();
    }

    public void tokenInvalid() {
        //        Intent intent = new Intent(QBaseActivity.this, LoginActivity.class);
        //        intent.putExtra(IntentFinal.INTENT_LOGIN_TOKEN_FAILE, 1);
        //        startActivityForResult(intent, 1);
        //        overridePendingTransition(R.anim.a_enter, R.anim.a_exit);
    }


    public void failureOperation(Object obj) {
        failureToast(obj);
        closeProgressDialog();
        clossRefresh();
    }

    protected void clossRefresh() {
    }

    public void showProgressDialog() {
        if (mProcessDialog == null) {
            if (getParent() != null) {
                mProcessDialog = new ProcessDialog(getParent());
            } else {
                mProcessDialog = new ProcessDialog(this);
            }
            mProcessDialog.setCancelable(false);
            mProcessDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        }
        if (!isFinishing()) {
            mProcessDialog.show();
        }
    }


    public void closeProgressDialog() {
        if (mProcessDialog != null)
            mProcessDialog.dismiss();
    }

    @Override
    protected void onDestroy() {

        super.onDestroy();
        //        if (myBroadCast != null)
        //            myBroadCast.onDestroy();
        if (mProcessDialog != null) {
            mProcessDialog.dismiss();
        }
        if (mDialog != null) {
            mDialog.dismiss();
        }

    }

    public void failureToast(Object object) {
        if (object != null) {
            String ts = object.toString();
            if (ts != null && ts.trim().length() > 0) {
                ToastUtils.showToast(ts);
            } else {
                if (isNetworkAvailable(this))
                    ToastUtils.showToast(
                            getString(R.string.app_request_failture));
                else
                    ToastUtils.showToast(
                            getString(R.string.app_request_network_error));
            }
        } else {
            if (isNetworkAvailable(this))
                ToastUtils.showToast(
                        getString(R.string.app_request_failture));
            else
                ToastUtils.showToast(
                        getString(R.string.app_request_network_error));
        }
    }

    public boolean isNetworkAvailable(Context context) {
        ConnectivityManager cm = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if (cm == null) {
            return false;
        } else {
            NetworkInfo[] info = cm.getAllNetworkInfo();
            if (info != null) {
                for (int i = 0; i < info.length; i++) {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
            return false;
        }
    }

    /**
     * 1圆角2圆
     */
    public void display(final ImageView imageView, String url,
                        int failureImage) {
        ImageLoader.getInstance().displayImage(url, imageView, getDisplayImageOptions(failureImage));
    }

    public DisplayImageOptions getDisplayImageOptions(int defaultImg) {
        DisplayImageOptions menu_options = new DisplayImageOptions.Builder()
                .cacheInMemory(true).cacheOnDisk(true)
                .resetViewBeforeLoading(true)
                //                .delayBeforeLoading(1000)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .displayer(new FadeInBitmapDisplayer(1000, true, true, false))
                .imageScaleType(ImageScaleType.EXACTLY)
                .showImageForEmptyUri(defaultImg).showImageOnFail(defaultImg)
                .showImageOnLoading(defaultImg).build();
        return menu_options;
    }

    public void sendMsg(Handler handler, int what, Object object) {
        Message message = handler.obtainMessage();
        message.what = what;
        message.obj = object;
        handler.sendMessage(message);
    }

    public List<ParamObj> GetNotParam() {
        int i = (int) Math.floor(Math.random() * 9000 + 1000);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", i + ""));
        String sign = GetSign.genPackageSign(list);

        List<ParamObj> paramObjs = new ArrayList<ParamObj>();
        paramObjs.add(new ParamObj("rnd", i + ""));
        paramObjs.add(new ParamObj("sign", sign));
        return paramObjs;
    }

    public List<ParamObj> GetHaveParam(List<ParamObj> paramObjs) {

        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();

        for (ParamObj paramObj : paramObjs) {
            list.add(new NameValuePairSign(paramObj.getName(), paramObj.getValue()));
        }
        String sign = GetSign.genPackageSign(list);

        paramObjs.add(new ParamObj("sign", sign));

        return paramObjs;
    }

    //    public void calcuAdersWidth(final View view, final float scale, final int width) {
    //
    //        view.post(new Runnable() {
    //            @Override
    //            public void run() {
    //                ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
    ////                DisplayMetrics displayMetrics = new DisplayMetrics();
    ////                getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    ////                layoutParams.height = (int) (displayMetrics.widthPixels * scale);
    //
    //                AppLog.D("layoutParams.widthlayoutParams.widthlayoutParams.width:" + layoutParams.width);
    //                layoutParams.height = (int) (width * scale);
    //                view.setLayoutParams(layoutParams);
    //                view.postInvalidate();
    //            }
    //        });
    //
    //    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //        if (resultCode == IntentFinal.LOGIN_SUCCESS_RESULT_CODE) {
        //            loginSuccess();
        //        }
    }

    //    public void loginSuccess() {
    //    }

    //    private MyBroadCast myBroadCast;

    //    private void initAppMsgBroad() {
    //        myBroadCast = new MyBroadCast(this, new String[]{IntentFinal.BROADCAST_QUIT_ACTIVITY});
    //        myBroadCast.setOnMyBroadCastListener(new MyBroadCast.MyBroadCastListener() {
    //            @Override
    //            public void onReceive(Context context, Intent intent) {
    //                if (intent.getAction().equals(IntentFinal.BROADCAST_QUIT_ACTIVITY) && quitOfParent()) {
    //                    finish();
    //                }
    //            }
    //        });
    //    }

    //    public boolean quitOfParent() {
    //        return true;
    //    }

    //    public String nameModify(String name) {
    //        return name.substring(0, 1) + "老师";
    //    }


    //    public void setWindowStatusBarColor(int colorResId) {
    //        try {
    //            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    //                Window window = this.getWindow();
    ////                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
    //                getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
    //                window.setStatusBarColor(getResources().getColor(colorResId));
    //                //底部导航栏
    //                //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
    //            }
    //        } catch (Exception e) {
    //            e.printStackTrace();
    //        }
    //    }


    //    private void editChildInfo() {
    ////        ToastUtils.showToast(R.string.app_child_info_invlid);
    //        showDialog();
    //
    //    }

    //    OrderChildInfoDialog orderChildInfoDialog;
    //
    //    private void showDialog() {
    //        if (orderChildInfoDialog == null) {
    //            orderChildInfoDialog = new OrderChildInfoDialog();
    //
    //        }
    //        orderChildInfoDialog.show(getSupportFragmentManager(), "OrderChildInfoDialog");
    //        orderChildInfoDialog.setOnSureListener(new OrderChildInfoDialog.OrderChildInfoListener() {
    //            @Override
    //            public void onSure() {
    //                startActivityForResult(new Intent(BaseActivity.this, ChildrenInfoEditActivity.class), 1);
    //                orderChildInfoDialog.dismiss();
    //            }
    //        });
    //    }

    public void showDailog(String text) {
        if (mDialog == null) {
            mDialog = new ProgressDialog(this);
        }
        mDialog.setMessage(text);
        //设置外面点击不可取消
        mDialog.setCancelable(false);
        mDialog.show();
    }

    public void hindDailog() {
        if (mDialog != null) {
            mDialog.hide();
        }
    }

    private List<String> mPermissionList = new ArrayList<>();
    private String[]     permissionss     = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.READ_PHONE_STATE
    };
    private static final int MY_PERMISSIONS_MORE=2;
    private static final int MY_PERMISSIONS_ONE=1;

    //单个权限申请
    public void initListPerMission(String permission){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this,
                        new String[]{permission},
                        MY_PERMISSIONS_ONE);
            }else {
                //TODO：已经有了权限了

            }
        }else {
            //TODO：已经有了权限了

        }
    }

    //多个权限一起申请
    public void initPerMission() {
        mPermissionList.clear();
        for (int i = 0; i < permissionss.length; i++) {
            if (ContextCompat.checkSelfPermission(this, permissionss[i]) != PackageManager.PERMISSION_GRANTED) {
                mPermissionList.add(permissionss[i]);
            } else {
                //TODO：已经有了权限了
                chekeHavePermission(permissionss[i]);
            }
        }
        if (!mPermissionList.isEmpty()) {//未授予的权限为空，表示都授予了
            //请求权限方法
            String[] permissions = mPermissionList.toArray(new String[mPermissionList.size()]);//将List转为数组
            ActivityCompat.requestPermissions(this, permissions, MY_PERMISSIONS_MORE);
        }else {
            //TODO：已经有了权限了

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        switch (requestCode){

            //单个权限
            case MY_PERMISSIONS_ONE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    //TODO：已经有了权限了
                    chekeHavePermission(permissions[0]);
                } else {
                    boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[0]);
                    if (TextUtils.equals(permissions[0], Manifest.permission.ACCESS_FINE_LOCATION)) {
                        if (showRequestPermission) {
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0);
                        }
                    } else {
                        if (showRequestPermission) {
                            Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            //        Uri uri = Uri.fromParts("package", context.getPackageName());
                            //        intent.setData(uri);
                            intent.setData(Uri.parse("package:" + getPackageName()));
                            startActivity(intent);
                        }
                    }
                }
                break;
            case MY_PERMISSIONS_MORE:
                for (int i = 0; i < grantResults.length; i++) {

                    if (grantResults[i] != PackageManager.PERMISSION_GRANTED) {
                        //判断是否勾选禁止后不再询问
                        boolean showRequestPermission = ActivityCompat.shouldShowRequestPermissionRationale(this, permissions[i]);
                        if (TextUtils.equals(permissions[i], Manifest.permission.ACCESS_FINE_LOCATION)) {
                            if (showRequestPermission) {
                                Intent intent = new Intent(
                                        Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                                startActivityForResult(intent, 0);
                            }
                        } else {
                            if (showRequestPermission) {
                                Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                //        Uri uri = Uri.fromParts("package", context.getPackageName());
                                //        intent.setData(uri);
                                intent.setData(Uri.parse("package:" + getPackageName()));
                                startActivity(intent);
                            }
                        }
                    } else {

                        //TODO：已经有了权限了
                        chekeHavePermission(permissions[i]);
                    }
                }

                break;

            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
                break;
        }

    }
    private void chekeHavePermission(String permision){

        //有内存卡读取权限了
        if (TextUtils.equals(permision,Manifest.permission.READ_EXTERNAL_STORAGE)||TextUtils.equals(permision,Manifest.permission.WRITE_EXTERNAL_STORAGE)){
            havePermis();
        }

        if (TextUtils.equals(permision,Manifest.permission.CAMERA)){
            haveReadCearm();
        }
    }

    /**
     * 读取相机的权限
     */
    public void haveReadCearm() {

    }

    /**
     *  读取内存卡权限有了
     */
    public void havePermis() {

    }


}
